from django.contrib.auth import get_user_model
from rest_framework.decorators import action
from rest_framework.exceptions import NotAuthenticated
from rest_framework.generics import GenericAPIView
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.permissions import (
    OperandHolder, OR,
)
from rest_framework.response import Response

from utils.restFramework.permissions import (
    IsOwner, IsAdmin
)
from utils.restFramework.viewSets import CustomerModelViewSet
from ..serializers import (
    CheckUsernameSerializer, CheckEmailSerializer, CheckPasswordSerializer, NoneSerializer,
    UserSerializer, CreateUserSerializer, RegisterCaptchaSerializer, ResetSelfPasswordSerializer
)

User = get_user_model()


# class UserViewSet(CustomerModelViewSet):
class UserViewSet(CustomerModelViewSet):
    queryset = User.objects.all()
    serializer_dict = {
        'user-username-check': CheckUsernameSerializer,
        'user-email-check': CheckEmailSerializer,
        'user-password-check': CheckPasswordSerializer,
        'user-get-register-captcha': RegisterCaptchaSerializer,
        'user-reset-password': ResetSelfPasswordSerializer,
        'user-reset-self-password': ResetSelfPasswordSerializer,
        'user-list': {
            'POST': CreateUserSerializer,
            'default': UserSerializer
        },
        'user-detail': UserSerializer,
        # 'user-upload-avatar': AvatarSerializer,
        # 'user-list': {
        #     'POST': CreateUserSerializer,
        #     'default': UserSerializer
        # },
        # 'default': UserSerializer
        'default': NoneSerializer
    }
    permissions_dict = {
        'user-detail': {
            'default': [IsAuthenticated | IsAdminUser]
        },
        'user-list': {
            'POST': [],
            'default': [IsAuthenticated | IsAdminUser]
        },
        'default': [OperandHolder(OR, IsOwner, IsAdmin)]
    }

    @action(detail=False, methods=['post'], url_path='check/username', url_name='username-check')
    def username_check(self, request):
        serializer = self.get_serializer_class()(data=request.data)
        serializer.is_valid(raise_exception=True)
        return Response({'message': '用户名可用'})

    @action(detail=False, methods=['post'], url_path='check/password', url_name='password-check')
    def password_check(self, request):
        serializer = self.get_serializer_class()(data=request.data)
        serializer.is_valid(raise_exception=True)
        return Response({'message': '密码可用'})

    @action(detail=False, methods=['post'], url_path='check/email', url_name='email-check')
    def email_check(self, request):
        serializer = self.get_serializer_class()(data=request.data)
        serializer.is_valid(raise_exception=True)
        return Response({'message': '邮箱可用'})

    @action(detail=False, methods=['post'], permission_classes=[IsOwner],
            url_path='reset_self_password', url_name='reset-self-password')
    def reset_self_password(self, request):
        serializer = self.get_serializer_class()(data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({'message': '密码修改成功'})

    @action(detail=False, methods=['post'], permission_classes=[(IsOwner or IsAdmin)], url_path='reset_password',
            url_name='reset-password')
    def reset_password(self, request):
        serializer = self.get_serializer_class()(data=request.data, context={'request': request})
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({'message': '密码修改成功'})

    @action(detail=False, methods=['post'], url_path='get_register_captcha', url_name='get-register-captcha')
    def get_register_captcha(self, request):
        serializer = self.get_serializer_class()(data=request.data)
        serializer.is_valid(raise_exception=True)
        captcha_key = serializer.send_mail()
        return Response({
            'message': '验证码已发送至邮箱',
            'data': {
                'captcha_key': captcha_key
            }
        })

    # @action(detail=True, methods=['put'], url_path='upload_avatar', url_name='upload-avatar')
    # def upload_avatar(self, request, pk=None):
    #     serializer = self.get_serializer_class()(data=request.data)
    #     serializer.is_valid(raise_exception=True)
    #     image = serializer.validated_data['avatar']
    #     user = request.user
    #     if user.avatar.name and user.avatar.name != settings.DEFAULT_AVATAR:  # 删除旧头像
    #         try:
    #             os.remove(user.avatar.path)
    #         except FileNotFoundError:
    #             pass
    #     filename = os.path.join('avatar', image.name)  # path/to/file 相对于MEDIA_ROOT的路径，/path/to/file 绝对路径
    #     filename = default_storage.save(filename, image)  # 使用默认存储好处之一，当文件重名时自动重命名
    #     user.avatar = filename
    #     user.save()
    #     return Response({'message': '头像上传成功'})


class GetSelfInfo(GenericAPIView):
    serializer_class = UserSerializer
    permission_classes = [IsOwner]

    def get(self, request):
        if not request.user:
            raise NotAuthenticated()
        serializer = self.get_serializer_class()
        self.check_object_permissions(self.request, request.user)
        return Response({
            'data': serializer(request.user, context={'request': request}).data
        })
